<template>
  <div class="orderingCount" v-if="menu_type">
    <template v-if="count > 0">
      <svg class="jj_icon" aria-hidden="true" @click.stop="handleCount(-1)">
        <use xlink:href="#icon-jiajian1"></use>
      </svg>
      <input v-model="count" />
    </template>
    <svg class="jj_icon" aria-hidden="true" @click.stop="handleCount(1)">
      <use xlink:href="#icon-jia"></use>
    </svg>
  </div>
</template>

<script>
import { useStore } from "vuex";
import { inject, ref } from "vue";
import { Toast } from "vant";
import { getOrderAdd, getOrderCancel } from "../../api/ordering";
import { useRoute } from "vue-router";

export default {
  name: "Count",
  props: ["menu_id", "menu_type", "order_count"],
  setup(props) {
    const store = useStore();
    const route = useRoute();
    //用户修改订单时触发
    const userHandle = inject("toUser");
    //选择数量
    const count = ref(props.order_count || 0);
    const obj = {
      user_id: store.state.user.profile.user_id,
      menu_id: props.menu_id,
      menu_type: props.menu_type,
      cancelValue: "noe",
    };
    // console.log(obj);
    //调整选择数量
    const handleCount = (value) => {
      store.commit("user/handleOrderingCount", value);
      count.value += value;
      if (value == 1) {
        getOrderAdd(obj).then((res) => {
          if (res.status == 200) {
            Toast("已加入我的菜单+1");
          } else {
            Toast("添加失败");
          }
        });
      } else {
        getOrderCancel(obj).then((res) => {
          if (res.status != 200) {
            return Toast("取消失败");
          }
        });
        if (count.value == 0) {
          return Toast("已取消");
        }
        Toast("已取消一份");
      }
      if (route.path == "/user") {
        userHandle();
      }
    };
    return { count, handleCount };
  },
};
</script>

<style scoped lang="less">
.jj_icon {
  width: 1.6em;
  height: 1.6em;
  vertical-align: -0.15em;
  fill: currentColor;
}
.orderingCount {
  display: flex;
  justify-content: center;
  align-items: center;
  input {
    width: 1.5rem;
    border: none;
    text-align: center;
    margin: 0 0.3rem;
    border-bottom: 1px solid #5f5f5f;
  }
}
</style>
